K.App('apps/common/ANotification', ['core/jQuery', 'core/Poller', 'core/Storage']).define(function(require) {

    var $ = require('core/jQuery'),
        Storage = require('core/Storage'),
        Poller = require('core/Poller');


    document.domain = window.location.host.replace(/([^\.]+)\./, '').replace(/([^\.]+)\./, '');

    return {
        'main' : function() {
            Storage.clear();
            this.ctxType = 'g';
            this.ctxTag = 'ctx';
            this.initNotification();
        },

        'initNotification' : function() {
            var _this = this,
                url = this.getURL();
            this.notification = new Poller({
                'url': url,
                'requestType': 'GET',
                'type': 'long',
                'cache': true,
                'callback': function(data) {
                    // data:{category:[1-消息提醒/2-任务提醒/3-即时聊天消息]}
                    data = $.parseJSON(data);
                    if(data && data.t === 'ctx') {
                        _this.seq = data.seq;
                        _this.ctxType = 'k';
                        _this.notification.url = _this.getURL();
                        // by jianqing: 不再使用ctx中的数据
                        // parent.K.fire('notification', {'data' : data.ctx});
                    } else if(data && data.t === 'refresh') {
                        _this.seq = data.seq || _this.seq;
                        _this.notification.url = _this.getURL();
                    } else if(data && data.t === 'inform') {
                        _this.seq = _this.seq + 1;
                        _this.notification.url = _this.getURL();
                        if (data.infos[0].c == ".ctx") {
                            parent.K.fire('notification', {'data' : data.infos[0].o});
                        } else {
                            parent.K.fire('presence', data.infos[0].c, data.infos[0].o);
                        }
                    } else {
                        _this.notification.stop();
                        K.log('Err Data:', data);
                    }
                }
            });

            this.notification.start();
        },

        'getURL' : function() {
            var uid = parent.K.Env.uid || parent.K.Env.UID ;
            return '/' + this.ctxType + '/' + ( + new Date()) + '/' + uid + '/' + (this.seq || this.ctxTag);
        }
    };
});
